package com.mach.platform.service;

import com.mach.platform.domain.base.Post;
import com.mach.platform.repository.PostRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @Description:   岗位实现类
 * @Package: com.mach.platform.com.mach.platform.service
 * @time 2018/4/19 0019 16:31
 */
@Service
public class PostServiceImpl implements PostService{

	@Autowired
	private PostRepo postRepo;

	@Autowired
	private EntityManager em;


	/**
	 * 保存
	 *
	 * @param post 保存的实体
	 * @return
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public Post save (Post post) {
		return postRepo.saveAndFlush(post);
	}

	/**
	 * 插入，批量保存
	 *
	 * @param list
	 * @return
	 */
	@Override
	public List<Post> insertObjInBatch (List<Post> list) {
		return null;
	}

	/**
	 * 更新
	 *
	 * @param post 跟新的实体
	 * @return
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public Post update (Post post) {
		Post originPost = postRepo.getById(post.getId());

		if (!originPost.getPid().equals(post.getPid())) {
			//如果修改了 父id，则查询旧的实体是否有子id，把所有的子id改为自己的父id，避免漏掉
			List<Post> sons = postRepo.findByPid(originPost.getId());
			if (sons.size() > 0) {
				sons.stream().forEach(item -> {
					item.setPid(originPost.getPid());
					em.merge(item);
				});
				em.flush();
				em.clear();
			}
		}

		return postRepo.saveAndFlush(post);
	}

	/**
	 * 删除--批量删除
	 *
	 * @param ids 批量删除id
	 * @return
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public int delete (Long[] ids) {

		return postRepo.deleteByIdIn(ids);
	}

	/**
	 * 获取列表数据
	 *
	 * @param pageable
	 * @param params
	 * @return
	 */
	@Override
	public Page<Post> list (Pageable pageable, Map params) {

		Page<Post> dbResult = postRepo.findAll(pageable);

		return dbResult;
	}

	/**
	 * 获取单体 数据
	 *
	 * @param id 获取详情的id
	 * @return
	 */
	@Override
	public Post info (Long id) {
		return null;
	}

}
